import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/common/LevelOption.dart';
import 'package:ichinesereader/models/evaluation/linguisticKnowledgeResult.dart';
import 'package:ichinesereader/models/report/evaluationLevelChartData.dart';
import 'package:ichinesereader/pages/teacher/knowledgeGauge.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/evaluationAccuracy.dart';
import '../../themes/appTheme.dart';

class SkillBuildingRecords extends StatefulWidget {
  static const String routeName = '/student/report/skillBuildingRecords';

  @override
  State<SkillBuildingRecords> createState() => _SkillBuildingRecords();
}

class _SkillBuildingRecords extends State<SkillBuildingRecords> {
  final box = Hive.box('appconfig');
  final ReportsController _reportsController = Get.find();
  bool isStudentOrIndividual = false;
  int _currentLevel = 1;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    try {
      isStudentOrIndividual =
          box.get(CacheManagerKey['nanhairole'].toString()) ==
                  Constants.NanhaiRole_Student ||
              box.get(CacheManagerKey['nanhairole'].toString()) ==
                  Constants.NanhaiRole_Individual;
      if (isStudentOrIndividual) {
        var level = box.get('UserLevel').toString().replaceAll('level', '');
        _currentLevel = int.tryParse(level) ?? 1;
      } else {
        _currentLevel = int.tryParse(box
                .get(CacheManagerKey['eveluationlevel'].toString())
                .toString()) ??
            1;
      }
    } catch (error) {
      Log.debug(error.toString());
      _currentLevel = 1;
    }

    if (isStudentOrIndividual) {
      Future.delayed(Duration(milliseconds: 100), (() {
        _reportsController
            .fetchLibraryKnowledgeUserData(_currentLevel.toString());
        _reportsController.fetchLibraryOverviewUserData();
      }));
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build student skill building');

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          children: [
            //Level Chips starts here
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  color: Get.isDarkMode
                      ? AppTheme.colors.darkTheme2
                      : Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(3.0)),
              padding: const EdgeInsets.only(left: 12),
              child: FormBuilderChoiceChip(
                spacing: 3.0,
                alignment: WrapAlignment.start,
                labelPadding: EdgeInsets.symmetric(
                  horizontal: 15.0,
                ),
                selectedColor: Get.isDarkMode
                    ? Colors.white
                    : Get.theme.primaryColorDark.withOpacity(0.9),
                elevation: 1.0,
                backgroundColor: Colors.transparent,
                decoration: InputDecoration(
                  //labelText: 'iChineseReader Levels',
                  labelStyle: Get.theme.textTheme.labelSmall,
                  border: InputBorder.none,
                ),
                initialValue: Constants.levelOptions
                    .where((element) =>
                        element.value.toString().replaceAll('level', '') ==
                        _currentLevel.toString())
                    .first,
                name: 'level_filter_chip',
                onChanged: (value) {
                  if (value == null) return;
                  var item = value as LevelOption;
                  int level =
                      int.parse(item.value.toString().replaceAll('level', ''));
                  box.put(CacheManagerKey['eveluationlevel'].toString(),
                      double.parse(level.toString()));
                  _reportsController
                      .fetchLibraryKnowledgeUserData(level.toString());
                },
                options: Constants.levelOptions
                    .where((element) => element.value != "level0")
                    .map((level) => FormBuilderChipOption<LevelOption>(
                          value: level,
                          child: Text(
                            level.label
                                .toString()
                                .replaceAll('Level 0', 'N/A')
                                .replaceAll('Level ', ''),
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold,
                              color: hexStringToHexInt(level.color.toString()),
                              letterSpacing: 0,
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ),
            //KnowledgeGauge starts here
            Padding(
              padding: EdgeInsets.only(top: 9.0),
              child: Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.black.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(3.0)),
                    padding: const EdgeInsets.all(12),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                              color: Get.isDarkMode
                                  ? AppTheme.colors.darkTheme2
                                  : Colors.white.withOpacity(0.3),
                              borderRadius: BorderRadius.circular(3.0)),
                          padding: const EdgeInsets.all(12),
                          margin: EdgeInsets.fromLTRB(1.0, 1.0, 6.0, 6.0),
                          child: Column(
                            children: [
                              Container(
                                height: 150,
                                child: KnowledgeGauge(
                                    studentName: 'Word',
                                    mode: 'water',
                                    progressData: new TotalProgress(
                                        progress: _reportsController
                                            .libraryKnowledgeUserData
                                            .value
                                            .word,
                                        total: _reportsController
                                            .libraryKnowledgeUserData
                                            .value
                                            .total)),
                              ),
                              Container(
                                  margin: EdgeInsets.only(top: 6.0),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 51, vertical: 3.0),
                                  decoration: BoxDecoration(
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Colors.black.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(4.5),
                                  ),
                                  child: Text(
                                    'Word'.tr,
                                    style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorDark
                                            : Get.theme.primaryColorLight),
                                  )),
                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              color: Get.isDarkMode
                                  ? AppTheme.colors.darkTheme2
                                  : Colors.white.withOpacity(0.3),
                              borderRadius: BorderRadius.circular(3.0)),
                          padding: const EdgeInsets.all(12),
                          margin: EdgeInsets.fromLTRB(1.0, 1.0, 6.0, 6.0),
                          child: Column(
                            children: [
                              Container(
                                  height: 150,
                                  child: KnowledgeGauge(
                                      studentName: 'Grammer',
                                      mode: 'water',
                                      progressData: new TotalProgress(
                                          progress: _reportsController
                                              .libraryKnowledgeUserData
                                              .value
                                              .grammer,
                                          total: _reportsController
                                              .libraryKnowledgeUserData
                                              .value
                                              .total))),
                              Container(
                                  margin: EdgeInsets.only(top: 6.0),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 39, vertical: 3.0),
                                  decoration: BoxDecoration(
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Colors.black.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(4.5),
                                  ),
                                  child: Text(
                                    "Grammar".tr,
                                    style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorDark
                                            : Get.theme.primaryColorLight),
                                  )),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            //Skill score chart starts here
            Container(
              margin: EdgeInsets.only(top: 9.0),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(6.0),
              ),
              width: context.width - 20,
              child: _reportsController.obx(
                (data) {
                  List<EvaluationLevelChart> chartData = [];
                  if (_reportsController
                          .quickReviewOverviewResult.value.icrLevel !=
                      null) {
                    _reportsController.quickReviewOverviewResult.value.icrLevel
                        ?.forEach((item) {
                      EvaluationLevelChart chart = EvaluationLevelChart(
                          item.level.toString(),
                          item.listeningAccuracy! / 10,
                          item.speakingScore?.toDouble(),
                          item.speakingAiScore! / 10,
                          item.readingAccuracy! / 10,
                          item.writingScore?.toDouble(),
                          0);
                      chartData.add(chart);
                    });
                  }
                  return EvaluationStackedLineChartForStudent(
                    levelChartData: chartData,
                    chartTitle: 'Skills'.tr,
                    xLabel: 'Score',
                    yLabel: '',
                    mode: 'quickReview',
                  );
                },
                onEmpty: Center(child: Text('')),
                onLoading: Container(),
                // onLoading: Center(
                //     child: CircularProgressIndicator(
                //   backgroundColor: Get.theme.primaryColorDark,
                //   strokeWidth: 9.0,
                // )),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
